<template>
  <div class="seriesdialog">
  <el-dialog
          :model-value="createSeriesDialogVisible"
          :title="createSeriesDialogTitle"
          :before-close="handleCancelCreateSeriesDialog"
          width="70%"
  >
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="快速创建" name="quickCreate">
        <el-row>
          <el-col :span="12">
            <span></span>
          </el-col>
          <el-col :span="12" class="mb10">
            <div align="right">
              <el-button type="primary" size="mini" @click="handleSelectVideos">
                <el-icon>
                  <plus />
                </el-icon>
                添加视频
              </el-button>
            </div>
          </el-col>
          <el-col :span="24">
            <el-table :data="selectedVideoList" style="width: 100%" >
              <el-table-column label="视频封面" :width="70">
                <template #default="{row}">
                  <div v-if="row.imageinfo" @click="handleAddRelImage(row)" style="cursor: pointer">
                    <el-image :src="row.imageinfo.viewurl + '&width=60&height=40'" />
                    <a class="delete-image" href="javascript:;" @click.stop="handleDeleteImage(row)">
                      <el-icon><circle-close/></el-icon>
                    </a>
                  </div>
                  <el-button v-else type="text" size="mini" @click="handleAddRelImage(row)">
                    选择封面
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="视频名称">
                <template #default="{row}">
                  <el-input placeholder="请输入视频名称" v-model.trim="row.name" class="input-w" size="small" style="width:99%" show-word-limit :minlength="2" :maxlength="30"/>
                </template>
              </el-table-column>
              <el-table-column label="视频类型" prop="mimetype" />
              <el-table-column label="视频信息">
                <template #default="{row}">
                  <div>
                    视频大小：
                    <span v-if="row.ext && row.ext.size">{{formatSize(row.ext.size)}}</span>
                    <span v-else>-</span>
                  </div>
                  <div class="mt10 mb10">
                    分辨率：
                    <span v-if="row.ext">{{row.ext.width + ' * ' + row.ext.height}}</span>
                    <span v-else>-</span>
                  </div>
                  <div>
                    时长：
                    <span v-if="row.ext">{{formatSeconToTime(row.ext.duration)}}</span>
                    <span v-else>-</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column v-if="createSeriesFormData.paytype == 1" label="付费状态">
                <template #default="{row}">
                  <el-switch
                          v-model="row.paytype"
                          inline-prompt
                          active-text="付费"
                          inactive-text="免费"
                          active-color="#F56C6C"
                          inactive-color="#67C23A"
                          :width="60"
                          :active-value="1"
                          :inactive-value="0"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="{row}">
                  <el-button type="text" size="mini" style="color: red" @click="handleDeleteSelectedVideo(row)">删除</el-button>
                  <el-button type="text" size="mini" @click="handleVideoPlay(row)">
                    预览
                  </el-button>
                  <screen-shot-button
                          type="text"
                          :row="row"
                          :is-multi="false"
                          @resultcallback="resultcallback"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24" class="mt15">
            <div align="middle">
              <el-button type="default" size="mini" @click="handleCancelCreateSeriesDialog">取消</el-button>
              <el-tooltip content="快速创建仅支持创建点播视频" placement="top">
                <el-button type="primary" size="mini" @click="handleConfirmCreateSeries">确认保存</el-button>
              </el-tooltip>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane v-for="seriesTpl in seriesTplData" :key="seriesTpl.tplid" :label="seriesTpl.name" :name="seriesTpl.tpltype">
        <create-form
                :ref="el => { if (el) formCreateSeriesRef[seriesTpl.tpltype] = el }"
                :to-dialog-data="createSeriesFormData"
                @cancelDialog="handleCancelCreateSeriesDialog"
                @getData="reloadSeriesList"
                :tpl-type-data="seriesTpl.tplid"
        />
      </el-tab-pane>
      <!--<el-tab-pane label="表单创建" name="formCreate">
        <create-form
          ref="formCreateSeriesRef"
          :to-dialog-data="createSeriesFormData"
          @cancelDialog="handleCancelCreateSeriesDialog"
          @getData="reloadSeriesList"
        />
      </el-tab-pane>-->
    </el-tabs>
    <rel-video-medium
            ref="relVideoMediumRef"
            :dialog-rel-video-visible="dialogRelVideoVisible"
            dialog-rel-video-mediatype="series"
            :dialog-rel-video-form-data="dialogRelVideoFormData"
            dialog-rel-video-title="选择点播视频"
            dialog-rel-action="createSeries"
            videotype="vod"
            @handleCancelVideoDialog="handleCancelVideoDialog"
            @handleVideoPlay="handleVideoPlay"
            @reloadMediaData="reloadVideoData"
    />
    <rel-image-medium
      ref="relImageMediumRef"
      dialog-rel-action="createSeries"
      dialog-rel-image-media-type="series"
      :dialog-rel-image-form-data="dialogRelImageFormData"
      dialog-rel-image-title="选择视频封面图"
      :dialog-rel-image-visible="dialogRelImageVisible"
      dialog-select-type="radio"
      @handleCancelRelImageDialog="handleCancelRelImageDialog"
      @handleVideoPlay="handleVideoPlay"
      @reloadMediaData="handleSelectedImage"
    />
  </el-dialog>
  </div>
</template>

<script>
  import {toRef, ref, reactive, nextTick} from 'vue'
  import {Plus} from '@element-plus/icons'
  import RelVideoMedium from "../../Medium/RelVideoMedium";
  import CreateForm from "../../../../series/CreateForm";
  import {quickCreateSeries} from "@/api/series/series";
  import {ElMessage} from 'element-plus'
  import {formatSize} from "@/utils/usage-config";
  import {getSeriesTplData} from "@/api/media/mediatype";
  import RelImageMedium from "../../Medium/RelImageMedium";
  import ScreenShotButton from "@/components/VideoScreenShot/ScreenShotButton";
  import { formatSeconToTime } from "@/utils/usage-config";

  export default {
    name: "CreateSeries",
    components: {Plus, RelVideoMedium, CreateForm, RelImageMedium, ScreenShotButton},
    props: {
      createSeriesDialogVisible: {
        type: Boolean,
        default: false
      },
      createSeriesDialogTitle: {
        type: String,
        default: ''
      },
      createSeriesDialogFormData: {
        type: Object,
        default() {
          return {
            mediaid: undefined,
            mediatype: undefined,
            groupid: undefined
          }
        }
      }
    },
    emits: ['handleCancelCreateSeriesDialog', 'reloadSeriesList', 'handleVideoPlay'],
    setup(props, context) {
      const createSeriesFormData = toRef(props, 'createSeriesDialogFormData')
      const selectedVideoList = ref([])
      const activeName = ref('quickCreate')
      const formCreateSeriesRef = ref([])
      /** 选择视频介质弹框相关参数开始 **/
      const dialogRelVideoVisible = ref(false)
      const dialogRelVideoFormData = reactive({
        groupid: undefined,
        datas: []
      })
      const relVideoMediumRef = ref(null)
      /** 选择视频介质弹框相关参数结束 **/
      const formData = reactive({
        mediaid: undefined,
        datas: []
      })
      const seriesTplData = ref([])
      /** 选择视频封面图相关参数开始 **/
      const dialogRelImageVisible = ref(false)
      const dialogRelImageFormData = reactive({
        datas: []
      })
      const relImageMediumRef = ref(null)
      const currentVideoid = ref(undefined)
      /** 选择视频封面图相关参数结束 **/

      /** 取消弹框 **/
      const handleCancelCreateSeriesDialog = () => {
        context.emit('handleCancelCreateSeriesDialog')
      }
      /** 获取子集模板列表 **/
      const handleGetSeriesTplList = () => {
        getSeriesTplData({mediatype: createSeriesFormData.value.mediatype, inuse: 1}).then(response => {
          if (response.errcode === 0) {
            seriesTplData.value = response.data
          }
        })
      }
      /** 删除已选中的视频 **/
      const handleDeleteSelectedVideo = (row) => {
        const index = getVideoIndex(row)
        if (index != -1) {
          selectedVideoList.value.splice(index, 1)
        }
      }
      /** 选择视频 **/
      const handleSelectVideos = () => {
        dialogRelVideoFormData.groupid = createSeriesFormData.value.groupid
        dialogRelVideoFormData.datas = []
        dialogRelVideoVisible.value = true
        nextTick(() => {
          relVideoMediumRef.value.init()
        })
      }
      /** 关闭视频介质弹框 **/
      const handleCancelVideoDialog = () => {
        dialogRelVideoVisible.value = false
      }
      /** 视频预览 **/
      const handleVideoPlay = (row) => {
        context.emit('handleVideoPlay', row)
      }
      /** 重新加载视频列表 **/
      const reloadVideoData = (data) => {
        data.forEach(row => {
          if (getVideoIndex(row.data) == -1) {
            row.data.paytype = createSeriesFormData.value.paytype
            selectedVideoList.value.push(row.data)
          }
        })
      }
      /** 获取选中的视频在视频列表中的索引 **/
      const getVideoIndex = (row) => {
        const index = selectedVideoList.value.findIndex(d => d.videoid == row.videoid)
        return index
      }
      /** 重新加载子集列表 **/
      const reloadSeriesList = () => {
        context.emit('reloadSeriesList')
      }
      /** 点击切换tab事件 **/
      const handleTabClick = (tab) => {
        if (tab.props.name == 'quickCreate') {
          selectedVideoList.value = []
        } else {
          nextTick(() => {
            if (formCreateSeriesRef.value[tab.props.name]) {
              formCreateSeriesRef.value[tab.props.name].init()
            }
          })
        }
      }
      /** 组合提交数据 **/
      const formatFormData = () => {
        formData.mediaid = createSeriesFormData.value.mediaid
        formData.datas = []
        selectedVideoList.value.forEach(row => {
          let imgs = []
          if (row.imageinfo) {
            imgs = [{
              type: 1,
              imgid: row.imageinfo.imgid
            }]
          }
          formData.datas.push({
            tplid: 'f904db468ed111ecb86d00163e30b2e1',
            name: row.name,
            paytype: row.paytype,
            videos: [
              {
                videoid: row.videoid,
                type: 1
              }
            ],
            imgs: imgs
          })
        })
      }
      /** 确定创建子集 **/
      const handleConfirmCreateSeries = () => {
        formatFormData()
        if (formData.datas.length <= 0) {
          ElMessage({type: 'warning', message: '请选择视频', duration: 2000})
        } else {
          quickCreateSeries(formData).then(response => {
            if (response.errcode == 0) {
              ElMessage({type: 'success', message: response.msg, duration: 2000})
              handleCancelCreateSeriesDialog()
              reloadSeriesList()
            }
          })
        }
      }
      const init = () => {
        currentVideoid.value = undefined
        handleGetSeriesTplList()
        activeName.value = 'quickCreate'
        selectedVideoList.value = []
      }

      /** 选择封面图相关方法开始 **/
      // 关闭弹框
      const handleCancelRelImageDialog = () => {
        dialogRelImageVisible.value = false
      }
      // 处理选择的图片介质
      const handleSelectedImage = (row) => {
        if (currentVideoid.value) {
          let videoIndex = selectedVideoList.value.findIndex(d => d.videoid === currentVideoid.value)
          selectedVideoList.value[videoIndex].imageinfo = row[0].data
        }
      }
      // 开启弹框
      const handleAddRelImage = (row) => {
        currentVideoid.value = row.videoid
        dialogRelImageFormData.datas = []
        dialogRelImageVisible.value = true
        nextTick(() => {
          relImageMediumRef.value.init()
        })
      }
      // 删除图片
      const handleDeleteImage = (row) => {
        let videoId = getVideoIndex(row);
        if (videoId !== -1) {
          delete selectedVideoList.value[videoId]['imageinfo']
        }
      }
      /** 选择封面图相关方法结束 **/
      const resultcallback = (data, row) => {
        if (data.length > 0) {
          let videoIndex = selectedVideoList.value.findIndex(d => d.videoid === row.videoid)
          selectedVideoList.value[videoIndex].imageinfo = data[0]
        }
      }


      return {
        handleCancelCreateSeriesDialog,
        createSeriesFormData,
        selectedVideoList,
        handleDeleteSelectedVideo,
        activeName,
        handleSelectVideos,
        dialogRelVideoVisible,
        dialogRelVideoFormData,
        handleCancelVideoDialog,
        handleVideoPlay,
        reloadVideoData,
        relVideoMediumRef,
        init,
        reloadSeriesList,
        formCreateSeriesRef,
        handleTabClick,
        handleConfirmCreateSeries,
        formatSize,
        seriesTplData,
        dialogRelImageFormData,
        dialogRelImageVisible,
        handleCancelRelImageDialog,
        handleSelectedImage,
        handleAddRelImage,
        relImageMediumRef,
        handleDeleteImage,
        resultcallback,
        formatSeconToTime
      }
    }
  }
</script>

<style lang="scss">
  .seriesdialog{
        .el-dialog__body{
            height: calc(65vh);
        }
    }
  .delete-image {
      display: flex;
      position: absolute;
      top:12px;
      right:0;
      padding: 3px;
      .el-icon{
        font-size:16px;
        color:#666;
        background: #fff;
        border-radius: 50%;
      }
    }
</style>
